package cn.drenal.gui;

import cn.drenal.common.Constants;
import cn.drenal.common.Main;
import cn.drenal.helper.JDBCHelper;
import cn.drenal.pet.PetAnimal;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.event.*;
import java.util.ArrayList;

public class GuiAdmin extends PetGui
{
    private JTable tableMangage = new JTable();
    private JPanel paneBtn = new JPanel();
    private JButton btnLogout = new JButton("注销");
    private JButton btnExit = new JButton("退出");
    private JScrollPane paneTableManage = new JScrollPane();

    @Override
    public void showGui()
    {
        this.setSize(600, 395);
        this.setTitle("宠物商店项目管理");
        this.refreshItemTable(JDBCHelper.queryAllData());
        super.showGui();
    }

    @Override
    protected void addComp()
    {
        setLayout(null);
        //表格
        tableMangage.getTableHeader().setReorderingAllowed(false);//列不能移动
        tableMangage.getTableHeader().setResizingAllowed(false);//不可拉动表格
        tableMangage.setEnabled(false);  //不可更改数据
        paneTableManage.setBounds(30, 30, 540, 300);
        paneTableManage.setViewportView(tableMangage);
        //按钮层
        btnLogout.setBounds(0, 0, 40, 30);
        btnExit.setBounds(0, 0, 40, 30);
        paneBtn.add(btnLogout);
        paneBtn.add(btnExit);
        paneBtn.setBounds(0, 330, 600, 80);
        //添加到GUIAdmin中
        this.add(paneBtn);
        this.add(paneTableManage);
    }

    @Override
    protected void addListener()
    {
        btnLogout.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                //关闭窗口
                dispose();
                //返回登录界面
                new GuiLogin().showGui();
                Main.consoleLog("管理员已注销。");
            }
        });
        btnExit.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                //关闭窗口
                dispose();
                //直接结束
                System.exit(0);
            }
        });
        tableMangage.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                //获取焦点行标
                int focusRowIndex = tableMangage.rowAtPoint(e.getPoint());
                if (focusRowIndex == -1) return;
                //设置被选中行焦点
                tableMangage.setRowSelectionInterval(focusRowIndex, focusRowIndex);

                if (e.getButton() == MouseEvent.BUTTON3)//如果鼠标右键
                {
                    JPopupMenu tabMenu = new JPopupMenu();
                    JMenuItem add = new JMenuItem("添加");
                    JMenuItem del = new JMenuItem("删除");
                    JMenuItem cha = new JMenuItem("修改");

                    //添加项的监听器
                    add.addActionListener(new ActionListener()
                    {
                        @Override
                        public void actionPerformed(ActionEvent e)
                        {
                            //弹出添加窗口
                            JTextField num = new JTextField();
                            JTextField type = new JTextField();
                            JTextField breed = new JTextField();
                            JTextField price = new JTextField();
                            JTextField quantity = new JTextField();

                            Object[] msg =
                                    {
                                            Constants.NUM_TEXT, num,
                                            Constants.TYPE_TEXT, type,
                                            Constants.BREED_TEXT, breed,
                                            Constants.PRICE_TEXT, price,
                                            Constants.QUANTITY_TEXT, quantity
                                    };
                            //添加一个输入窗口
                            int option = JOptionPane.showConfirmDialog(null, msg, "添加项目", JOptionPane.OK_CANCEL_OPTION);
                            //点击确定后的操作
                            if (option == JOptionPane.OK_OPTION)
                            {
                                String dataNum = num.getText().trim();
                                String dataType = type.getText().trim();
                                String dataBreed = breed.getText().trim();
                                String trimPrice = price.getText().trim();
                                String trimQuantity = quantity.getText().trim();
                                //判断是否存在空串
                                boolean conditionNull = dataNum.equals("") || dataType.equals("") || dataBreed.equals("") || trimPrice.equals("") || trimQuantity.equals("");
                                if (conditionNull)
                                {
                                    JOptionPane.showMessageDialog(null, "此操作每项都为必填项，请重新输入！", "Error", JOptionPane.WARNING_MESSAGE);
                                    return;
                                }
                                try
                                {
                                    double dataPrice = Double.parseDouble(price.getText().trim());
                                    if (dataPrice < 0)
                                        throw new NumberFormatException();
                                }
                                catch (NumberFormatException ex)
                                {
                                    JOptionPane.showMessageDialog(null, "价格输入格式错误，请重新输入！", "Error", JOptionPane.WARNING_MESSAGE);
                                    return;
                                }
                                try
                                {
                                    int dataQuantity = Integer.parseInt(quantity.getText().trim());
                                    if (dataQuantity < 0)
                                        throw new NumberFormatException();
                                }
                                catch (NumberFormatException ex)
                                {
                                    JOptionPane.showMessageDialog(null, "数量输入格式错误，请重新输入！", "Error", JOptionPane.WARNING_MESSAGE);
                                    return;
                                }
                                //添加数据进数据库
                                PetAnimal animal = new PetAnimal(dataNum, dataType, dataBreed, Double.parseDouble(trimPrice), Integer.parseInt(trimQuantity));
                                JDBCHelper.addPetAnimal(animal);
                                Main.consoleLog("添加完成。");
                                //刷新表
                                refreshItemTable(JDBCHelper.queryAllData());
                            }
                        }
                    });
                    //删除项的监听器
                    del.addActionListener(new ActionListener()
                    {
                        @Override
                        public void actionPerformed(ActionEvent e)
                        {
                            //进行删除操作
                            JDBCHelper.delPetAnimal((String) tableMangage.getValueAt(focusRowIndex, 0));
                            Main.consoleLog("内容已删除。");
                            //刷新表
                            refreshItemTable(JDBCHelper.queryAllData());
                        }
                    });
                    //修改项的监听器
                    cha.addActionListener(new ActionListener()
                    {
                        @Override
                        public void actionPerformed(ActionEvent e)
                        {
                            //弹出修改窗口
                            int colCnt = tableMangage.getColumnCount();
                            int rowInd = tableMangage.getSelectedRow();
                            Object[] data = new String[colCnt];
                            //获得每列数据
                            for (int i = 0; i < colCnt; i++)
                            {
                                data[i] = tableMangage.getValueAt(rowInd, i);
                            }

                            JTextField num = new JTextField((String) data[0]);
                            JTextField type = new JTextField((String) data[1]);
                            JTextField breed = new JTextField((String) data[2]);
                            JTextField price = new JTextField((String) data[3]);
                            JTextField quantity = new JTextField((String) data[4]);

                            Object[] msg =
                                    {
                                            Constants.NUM_TEXT, num,
                                            Constants.TYPE_TEXT, type,
                                            Constants.BREED_TEXT, breed,
                                            Constants.PRICE_TEXT, price,
                                            Constants.QUANTITY_TEXT, quantity
                                    };

                            int option = JOptionPane.showConfirmDialog(null, msg, "修改项目", JOptionPane.OK_CANCEL_OPTION);

                            if (option == JOptionPane.OK_OPTION)
                            {
                                String dataNum = num.getText().trim();
                                String dataType = type.getText().trim();
                                String dataBreed = breed.getText().trim();
                                String trimPrice = price.getText().trim();
                                String trimQuantity = quantity.getText().trim();
                                //判断是否存在空串
                                boolean conditionNull = dataNum.equals("") || dataType.equals("") || dataBreed.equals("") || trimPrice.equals("") || trimQuantity.equals("");
                                if (conditionNull)
                                {
                                    JOptionPane.showMessageDialog(null, "此操作每项都为必填项，请重新输入！", "Error", JOptionPane.WARNING_MESSAGE);
                                    return;
                                }
                                try
                                {
                                    double dataPrice = Double.parseDouble(price.getText().trim());
                                    if (dataPrice < 0)
                                        throw new NumberFormatException();
                                }
                                catch (NumberFormatException ex)
                                {
                                    JOptionPane.showMessageDialog(null, "价格输入格式错误，请重新输入！", "Error", JOptionPane.WARNING_MESSAGE);
                                    return;
                                }
                                try
                                {
                                    int dataQuantity = Integer.parseInt(quantity.getText().trim());
                                    if (dataQuantity < 0)
                                        throw new NumberFormatException();
                                }
                                catch (NumberFormatException ex)
                                {
                                    JOptionPane.showMessageDialog(null, "数量输入格式错误，请重新输入！", "Error", JOptionPane.WARNING_MESSAGE);
                                    return;
                                }
                                //修改操作
                                PetAnimal animal = new PetAnimal(dataNum, dataType, dataBreed, Double.parseDouble(trimPrice), Integer.parseInt(trimQuantity));
                                JDBCHelper.updatePetAnimal(animal, (String) data[0]);
                                Main.consoleLog("已进行修改。");
                                //修改后刷新表
                                refreshItemTable(JDBCHelper.queryAllData());
                            }
                        }
                    });
                    //添加表项
                    tabMenu.add(add);
                    tabMenu.add(del);
                    tabMenu.add(cha);
                    tabMenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });
    }

    //刷新表单
    public void refreshItemTable(ArrayList<PetAnimal> dataList)
    {
        //表头
        String[] tabHead = {Constants.NUM_TEXT, Constants.TYPE_TEXT, Constants.BREED_TEXT, Constants.PRICE_TEXT, Constants.QUANTITY_TEXT};
        //设置表单体
        String[][] tabBody = JDBCHelper.listToArray(dataList);
        TableModel model = new DefaultTableModel(tabBody, tabHead);
        tableMangage.setModel(model);
        //临时生成insert语句用
        //fun(dataList);
    }

    //打印insert语句
    public void fun(ArrayList<PetAnimal> data)
    {
        System.out.println("insert into Pet(num, type, breed, price, quantity)\n" +
                "values");
        for (int i = 0; i < data.size(); i++)
        {
            PetAnimal t = data.get(i);
            System.out.print("(\"" + t.getNum() + "\", \"" + t.getType() + "\", \"" + t.getBreed() + "\", " + t.getPrice() + ", " + t.getQuantity() + ")");
            if (i != data.size() - 1)
                System.out.println(",");
            else
                System.out.println(";");
        }
    }
}

